<template>
  <div>
    <img @click="selectFile" src="../assets/image/imageMsgIcon.png" alt="imageMsgIcon">
    <!-- #TODO: @pablo v-on:change 可以修改为修饰符的形式 @change -->
    <input name="mediaFile" type="file" @change="sendImg">
  </div>
</template>

<style scoped>
input {
  display: none;
}
</style>
<script>
import ConstUrl from '../const.json'
export default {
  props: ['jsonPkg', 'lastDialogID'],
  data () {
    return {
      jsondata: {
        commonKey: 100,
        appKey: 4,
        userID: this.$q.cookies.get('userID'),
        data: {
          senderID: this.$q.cookies.get('userID'),
          receiverID: null,
          msgType: null,
          groupID: null,
          lastDialogID: null,
          textMsg: null,
          contentType: 3,
          gpsLatitude: this.$q.cookies.get('gpsLatitude'),
          gpsLongtitude: this.$q.cookies.get('gpsLongtitude')
        }
      }
    }
  },
  // mounted () {
  //   this.initData()
  // },
  methods: {
    initData () {
      this.jsondata.data.msgType = this.jsonPkg.data.msgType
      this.jsondata.data.receiverID = this.jsonPkg.data.receiverID
      this.jsondata.data.lastDialogID = this.lastDialogID
      this.jsondata.data.groupID = this.jsonPkg.data.groupID
    },
    selectFile () {
      this.initData()
      document.getElementsByTagName('input')[0].click()
    },
    getFormData () {
      /* #TODO: @pablo let和const的选择，参考之前review意见，下同 */
      const img = document.querySelector('[type=file]')
      const formdata = new FormData()
      formdata.append('gdData', JSON.stringify(this.jsondata))
      formdata.append('mediaFile', img.files[0])
      return formdata
    },
    async httpPost (pkg, f) {
      const {
        data: { data }
      } = await this.$http({
        url: ConstUrl.url,
        method: 'post',
        data: pkg,
        header: {
          Accept: '*/*',
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          'X-Requested-With': 'XMLHttpRequest'
        }
      })
      f(data)
    },
    sendImg () {
      const data = this.getFormData()
      /* #TODO: @pablo 这里为什么要写原生的XMLHttpRequest？不是可以直接用axios发起吗？ this.$http()这样 */
      this.httpPost(data, data => console.log('imgSend sucess data is ', data))
    }
  }
}
</script>
